package com.hb.trade.server.center.sys.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hb.core.pojo.center.sys.entity.DicType;
import com.hb.core.pojo.parent.MPBaseController;
import com.hb.core.pojo.parent.PageResult;
import com.hb.trade.server.center.sys.service.DicTypeService;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.MsgUtil;
import org.fzzn.core.util.encrypt.PinyinUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 字典类型表 前端控制器
 *
 * @author zhaojk
 * @since 2021-05-21
 */
@RestController
public class DicTypeController extends MPBaseController<DicType, DicTypeService> {

    public DicTypeController(DicTypeService service) {
        super(service);
    }

    @PostMapping("/dicType/pageDicTypes")
    public Message<PageResult<DicType>> pageDicTypes(@RequestBody DicType dicType) {
        Page<DicType> dicTypePage = dicType.pages();
        QueryWrapper<DicType> wrapper = DicType.wrapper();
        page(wrapper, dicTypePage);
        return MsgUtil.success(PageResult.get(dicTypePage));
    }

    @PostMapping("/dicType/listDicTypes")
    public Message<List<DicType>> listDicTypes(@RequestBody DicType dicType) {
        QueryWrapper<DicType> wrapper = dicType.buildWrapper();
        wrapper.orderByAsc("type_name");
        List<DicType> dicTypes = service.list(wrapper);
        return MsgUtil.success(dicTypes);
    }

    @PostMapping("/dicType/updateDicType")
    public Message<Boolean> updateDicType(@RequestBody DicType dicType) {
        String typeCode = dicType.getTypeCode();
        if (StrUtil.isEmpty(typeCode)) {
            dicType.setTypeCode(PinyinUtil.getPingYin(dicType.getTypeName()));
        }
        boolean saveOrUpdate = saveOrUpdate(dicType);
        return MsgUtil.success(saveOrUpdate);
    }

    @PostMapping("/dicType/deleteDicTypes")
    public Message<Boolean> deleteDicTypes(@RequestBody List<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        UpdateWrapper<DicType> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("delete_flag", 1)
                .set("update_time", DateUtil.date())
                .in("id", ids);
        boolean remove = service.update(updateWrapper);
        return MsgUtil.success(remove);
    }
}
